<!-- eslint-disable vue/valid-v-on -->
<!-- eslint-disable vue/max-attributes-per-line -->
<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            type="warning"
            size="small"
            @click="$router.push('/import')"
            >excel导入</el-button
          >
          <el-button
            v-allow="'export-excel'"
            type="danger"
            size="small"
            @click="handleDownload"
            >excel导出</el-button
          >
          <el-button type="primary" size="small" @click="showDialog = true"
            >新增员工
            <!-- <el-dialog title="新增员工" :visible.sync="showDialog">
              <addor-edit v-if="showDialog" />
            </el-dialog> -->
          </el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="list" sort-change="hSortChange">
          <el-table-column label="序号" type="index" :index="hIndex" />
          <el-table-column label="电话" prop="mobile" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <img class="img-container" :src="scope.row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            sortable="custom"
          />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <!-- @click="$router.push('/employees/detail?id=' + scope.row.id)" -->
              <el-button
                type="text"
                size="small"
                @click="
                  $router.push(
                    '/employees/detail/' +
                      scope.row.id +
                      '/' +
                      scope.row.username
                  )
                "
                >查看</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row)"
                >分配角色</el-button
              >
              <el-button type="text" size="small" @click="hDel(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination layout="prev, pager, next" />
        </el-row>

        <!-- :current-page="currentPage" 设置当前页码
          :page-sizes="[100, 200, 300, 400]" 选择每页提供的条数
          :page-size="100" 当前每页提供的条数
          layout="total, sizes, prev, pager, next, jumper"
          :total="400"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" -->
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[2, 5, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <el-dialog title="新增员工" :visible.sync="showDialog">
          <addor-edit
            v-if="showDialog"
            @close="showDialog = false"
            @update-empolyee="hUpdateEmpolyee"
          />
        </el-dialog>
        <el-dialog
          title="分配角色"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="showDialogRole"
        >
          <assign-role
            v-if="showDialogRole"
            :employee-id="curEmployeeId"
            @close="showDialogRole = false"
          />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
// 引入组件
import AssignRole from './assignRole.vue'
import addorEdit from './empDialog'
// import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployees } from '@/api/employees'
import employeesENUM from '@/constant/employees'
console.log(employeesENUM.hireType)
const map = employeesENUM.hireType.reduce((acc, cur) => {
  acc[cur.id] = cur.value
  return acc
}, {})

export default {
  components: {
    // eslint-disable-next-line vue/no-unused-components
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      list: [],
      currentPage: 1,
      pageSize: 2,
      total: 0,
      showDialog: false,
      tHeader: [],
      showDialogRole: false,
      curEmployeeId: ''
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 让每页的序号不是从1开始，而是延续上一页的序号
    hIndex(index) {
      // console.log(index)
      // 当前序号 + ( 当前页数 - 1 ) * 每页条数 + 1
      return index + (this.currentPage - 1) * this.pageSize + 1
    },
    hSortChange(e) {
      console.log(e)
    },
    format(id) {
      // console.log(id)
      return map[id] || '未知'
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.currentPage, this.pageSize)
        console.log(res)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
        this.$message.error('加载员工数据失败')
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      // 更新每页显示的条数
      this.currentPage = 1
      this.pageSize = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.loadEmployeeList()
    },
    async doDel(id) {
      try {
        const res = await delEmployees(id)
        console.log('delEmployee', res)
        // 如果删除第最后一页（例如4）的最一条数据之后，页面会显示不正常
        if (this.list.length === 1) {
          this.currentPage--
          if (this.currentPage <= 0) {
            this.currentPage = 1
          }
        }
        // 重发请求
        this.loadEmployeeList()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？')
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    // 收到子组件抛出的添加成功的事件
    hUpdateEmpolyee() {
      this.showDialog = false
      this.total++
      this.currentPage = Math.ceil(this.total / this.pageSize)
      this.loadEmployeeList()
    },
    async handleDownload() {
      this.downloadLoading = true
      const res = await getEmployeeList(this.currentPage, this.total)
      const list = res.data.rows
      import('@/vendor/Export2Excel').then(excel => {
        const data = this.formatJson(list)
        const tHeader = this.tHeader
        console.log(list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename, // 定义文件名
          autoWidth: this.autoWidth, // 定义表格宽度 ,默认是true
          bookType: this.bookType // 定义文件格式,默认xlsx
        })
        this.downloadLoading = false
      })
    },
    formatJson(list) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      this.tHeader = Object.values(map)
      return list.map(item => {
        return Object.keys(map).map(key => {
          return item[key]
        })
      })
      // console.log(list)
      // return list
    },
    hAssignRole({ id }) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curEmployeeId = id
    }
  }
}
</script>
<style scoped lang="scss">
// 样式穿透， 有三种写法：
// 1. >>>       在less中使用
// 2. /deep/    在less中使用
// 3. ::v-deep  在scss中使用
.img-container {
  border-radius: 50%;
  width: 50px;
}
</style>
